Ext.onReady(function() {

	Ext.QuickTips.init();

    var servlet = "/cardioSHARE/query";
    var taskId;
    var gridPanel;
    
    var renderLinks = function(value, metadata) {
        if (value.match(/^http:/)) {
        	return String.format("<a href='{0}'>{1}</a>", value, value);
        } else {
        	return value;
        }
    }

    var pollServlet = function(statusBar) {
        
        if (!(statusBar instanceof Object)) {
            statusBar = Ext.getCmp(statusBar);
            statusBar.showBusy();
        }
        
        Ext.Ajax.request({
            url: servlet,
            params: { poll: taskId },
            success: function(result, response) {
                
                result = Ext.util.JSON.decode(result.responseText);
	            if (result instanceof Object) {
	                
	                statusBar.clearStatus();
	                submit.enable();
	                
	                if (result.error) {
	                    statusBar.setStatus({
	                        text: result.error,
	                        iconCls: "x-status-error"
	                    });
	                    return;
	                } else if (result.rows.length == 0) {
	                    statusBar.setText("Query returned no results.");
	                    return;
	                } else {
	                    statusBar.setText("Done.");
	                }
	                
	                var store = new Ext.data.SimpleStore({
	                    fields: result.fields
	                });
	                store.loadData(result.rows);
	                
	                var columns = [];
	                for (var i=0; i<result.fields.length; ++i) {
	                    columns.push({
	                        header: result.fields[i],
	                        dataIndex: result.fields[i],
	                        sortable: true,
	                        renderer: renderLinks
	                    });
	                }
	                gridPanel = new Ext.grid.GridPanel({
	                    store: store,
	                    columns: columns,
	                    viewConfig: { forceFit: true },
	                    stripeRows: true,
	                    width: 'auto',
	                    autoHeight: true,
	                    maxHeight: 600,
	                    title: "Query results"
	                });
	                
	                gridPanel.render("result-table");
	                var pos = formPanel.getPosition();
	                window.scroll(pos[0], pos[1]);
	                
	            } else {
	            
	                if (result) {
	                    statusBar.setText( "<xmp style='margin: inherit; font-family: inherit;'>" + result + "</xmp>" );
	                }
                    (function(){ pollServlet(statusBar) }).defer(2000);
                    
	            }
            },
            failure: function(response, options) {
                statusBar.setStatus({
	               text: "Error " + response.status + " (" + response.statusText + ") during request",
	               iconCls: "x-status-error"
	            });
            }
        });
        
    };
    
    var tabPanel = new Ext.TabPanel({
        renderTo: 'tabs',
        width: 'auto',
        activeTab: 0,
        frame: false,
        defaults: { autoHeight: true },
        items: [
            { contentEl: 'query', title: 'Query' },
            { contentEl: 'browse', title: 'Browse' }
        ]
    });

	var formPanel = new Ext.FormPanel({
	    frame: true,
	    labelAlign: "top",
	    
	    items: [
	        new Ext.form.TextArea({
	            fieldLabel: "SPARQL query",
	            name: "query",
	            width: "99%",
	            height: "8em"
	        })
	    ],
	    
	    bbar: new Ext.StatusBar({
	        defaultText: "Ready.",
	        defaultIconCls: "",
	        id: "query-status-bar"
	    })
	});
	
	var submit = formPanel.addButton("Submit", function() {
	    formPanel.getForm().submit({
	        url: servlet,
	        success: function(form, action) {
	            taskId = action.result.taskId;
	            pollServlet("query-status-bar");
	            submit.disable();
	            if (gridPanel) {
	                gridPanel.destroy();
	            }
	        },
	        error: function(form, action) {
	            alert(error);
	        }
	    })
	});
	
	formPanel.render("query-form");
});
